package com.smartTerminal.ex;

import java.net.ConnectException;
import java.net.SocketTimeoutException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.ws.WebServiceException;

import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

public class CustomExceptionResolver implements HandlerExceptionResolver {
	 @Override
	    public ModelAndView resolveException(HttpServletRequest request,
	            HttpServletResponse response, Object handler, Exception ex) {

	        ex.printStackTrace();
	        CustomException customException = null;

	        //如果抛出的是系统自定义的异常则直接转换
	        if(ex instanceof WebServiceException) {
	        	String sonEX = ex.getCause().toString();
	        	if(sonEX.contains("ConnectException")){
	        		customException = new CustomException("连接服务器超时，请返回首页重试。。。");
	        	}else if(sonEX.contains("SocketTimeoutException")){
	        		customException = new CustomException("请求服务器超时，请返回首页重试。。。");
	        	}else{
	        		customException = new CustomException("系统未知错误,请联系管理员。。。");
	        	}
	        }else {
	            //如果抛出的不是系统自定义的异常则重新构造一个未知错误异常
	            //这里我就也有CustomException省事了，实际中应该要再定义一个新的异常
	            customException = new CustomException("系统错误。。。");
	        }

	        //向前台返回错误信息
	        ModelAndView modelAndView = new ModelAndView();
	        modelAndView.addObject("tips", customException.getMessage());
	        modelAndView.setViewName("/user/error");

	        return modelAndView;
	    }
}
